package ru.netcracker.jcl.main;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
import java.util.StringTokenizer;

import ru.netcracker.jcl.command.BadCommandException;
import ru.netcracker.jcl.command.CommandFactory;
import ru.netcracker.jcl.command.ICommand;
import ru.netcracker.jcl.net.Server;

public class JavaCommandLine implements Runnable {
	
	private final static String[] commands = new String[] {"echo 123 123 < C:\\test.txt"};
	private final InputStream inputStream;
	private final OutputStream outputStream;
	
	
	public JavaCommandLine(InputStream inputStream, OutputStream outputStream) {
		this.inputStream = inputStream;
		this.outputStream = outputStream;
	}
	
	public JavaCommandLine() {
		this.inputStream = System.in;
		this.outputStream = System.out;
	}
	
	public static void main(String[] args) throws Exception {
//		String consoleEncoding = System.getProperty("consoleEncoding");
//		if (consoleEncoding != null) {
/*		    try {
		        System.setOut(new PrintStream(System.out, true, "utf8"));
		    } catch (java.io.UnsupportedEncodingException ex) {
		        System.err.println("Unsupported encoding set for console: " + "cp866");
		    }*/
//		}
//		System.setErr(new PrintStream(System.err, true, "cp866"));
//		System.out.println("Мышка сушек насушила");
//		System.err.println("Мышка сушек насушила");
		
		args = new String[]{"4444"};
		if (args.length > 0) {
			Server server = new Server(Integer.parseInt(args[0]));
			new Thread(server).start();
		}
		new JavaCommandLine().run();
	}

	private void processCommand(String commandWithArgs) throws BadCommandException, IOException {
		StringTokenizer tokenizer = new StringTokenizer(commandWithArgs, " ><", true);
		if (tokenizer.countTokens() == 0) {
			throw new BadCommandException();
		}
		String commandName = tokenizer.nextToken();
		List<String> commandArgs = new LinkedList<String>();
		String outputFile = null;
		String inputFile = null;
		while (tokenizer.hasMoreTokens()) {
			String token = tokenizer.nextToken();
			if ((token.equals(">")) || (token.equals("<"))) {
				char symbol = token.charAt(0);
				while (tokenizer.hasMoreTokens()) {
					token = tokenizer.nextToken();
					if (!token.equals(" ")) {
						break;
					}
				}
				if (token.equals(" ")) {
					throw new BadCommandException();
				}
				if (symbol == '>') {
					outputFile = token;
				} else {
					inputFile = token;
				}
				continue;
			}
			if (!token.equals(" ")) {
				commandArgs.add(token);
			}
		}

		ICommand command = CommandFactory.getCommand(commandName);
		if (inputFile != null) {
			command.setInputStream(new FileInputStream(inputFile));
		} else {
			command.setInputStream(null);
		}
		if (outputFile != null) {
			command.setOutputStream(new FileOutputStream(outputFile));
		} else {
			command.setOutputStream(outputStream);
		}
		command.run(commandArgs);
	}
		
		
	
	@Override
	public void run() {
/*		for (String commandWithArgs : commands) {
			try {
				processCommand(commandWithArgs);
			} catch (BadCommandException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
*/		
		Scanner scanner = new Scanner(inputStream);
		PrintStream outputPrintStream = new PrintStream(outputStream);
		while (scanner.hasNext()) {
			try {
				processCommand(scanner.nextLine());
			} catch (BadCommandException e) {
				outputPrintStream.println("Bad command");
			} catch (IOException e) {
				outputPrintStream.println("Bad file name");
			}
		}
		
	}
}
